package com.info.zhiduoduo.pay.sdk.dayspaysdk.core;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * ͳһ������
 * 
 * @author luoyunqiu
 * 
 */
public class CommonInterceptor implements Filter {
	private static final String CHARSET_ENCODE_PARAM_NAME = "Charset";
	private FilterConfig config = null;
	private String encoding = "UTF-8";
	private static ThreadLocal<HttpServletRequest> requests = new ThreadLocal<HttpServletRequest>();
	private static ThreadLocal<HttpServletResponse> responses = new ThreadLocal<HttpServletResponse>();

	public static HttpServletRequest getRequest() {
		return (HttpServletRequest) requests.get();
	}

	public static HttpServletResponse getResponse() {
		return (HttpServletResponse) responses.get();
	}

	public static HttpSession getSession() {
		if (getRequest() != null)
			return (HttpSession) getRequest().getSession();
		else
			return null;
	}

	public static HttpSession getSession(boolean create) {
		return (HttpSession) getRequest().getSession(create);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// �����ַ���.
		request.setCharacterEncoding(encoding);
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		requests.set(req);
        responses.set(resp);
        chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		this.config = config;
		if (this.config.getInitParameter(CHARSET_ENCODE_PARAM_NAME) != null) {
			encoding = config.getInitParameter(CHARSET_ENCODE_PARAM_NAME);
		}
	}

}
